using System.Text;

namespace Tycho.Parser.Peg {
    public class StringProduction : Production {
        public StringProduction () {
            ErrorInformation = new ProductionErrorInformation ("string");
        }

        public static Terminal CreateTerminal () {
            return new Terminal (new StringProduction ());
        }

        protected override ParseResult ReallyParse (char[] source, int startIndex, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            int index = startIndex;
            if (source[index] == '\'') {
                index++;
                int stringStartIndex = index;
                var stringValue = new StringBuilder ();

                while (true) {
                    if (++index >= source.Length) return null;

                    if (source[index] == '\'') {
                        if (++index >= source.Length) break;
                        
                        if (source[index] == '\'') {
                            stringValue.Append(new string (source, stringStartIndex, index - stringStartIndex));

                            if (++index >= source.Length) return null;
                            stringStartIndex = index;
                        } else {
                            break;
                        }
                    }
                }

                stringValue.Append(new string (source, stringStartIndex, index - stringStartIndex - 1));

                SourceInformation sinfo = parseEnvironment.SourceFileInformation.CreateSourceInformation (startIndex, index - startIndex);
                return new ParseResult (index, new StringTerm (stringValue.ToString(), sinfo), context);
            } else {
                return null;
            }
        }
    }
}